package com.insmess.speech.sdk.template;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.insmess.speech.sdk.dto.TextRequestDto;
import com.insmess.speech.sdk.dto.TextResponseDto;
import lombok.SneakyThrows;

public class InsmessTextTemplate {
    private String url;

    public InsmessTextTemplate(String url) {
        this.url = url;
    }

    /**
     * 根据内容添加标点
     * @return
     */
    @SneakyThrows
    public TextResponseDto textNumberReverseRequest(String text) {
        HttpRequest http = HttpUtil.createPost(url + "/number_reverse");
        //构造请求体
        TextRequestDto textRequestDto = new TextRequestDto();
        textRequestDto.setText(text);
        TextResponseDto textResponseDto = getTextResponseDto(http, textRequestDto);
        return textResponseDto;
    }

    /**
     * 根据内容添加标点
     * @return
     */
    @SneakyThrows
    public TextResponseDto textPuncRequest(String text) {
        HttpRequest http = HttpUtil.createPost(url + "/punc");
        //构造请求体
        TextRequestDto textRequestDto = new TextRequestDto();
        textRequestDto.setText(text);
        TextResponseDto textResponseDto = getTextResponseDto(http, textRequestDto);
        return textResponseDto;
    }

    /**
     * HTTP发送http请求并将结果转换
     * @param http
     * @throws JsonProcessingException
     */
    private TextResponseDto getTextResponseDto(HttpRequest http, TextRequestDto textRequestDto) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(textRequestDto);
        HttpResponse resp = http.body(json).execute();
        String body = resp.body();
        TextResponseDto textResponseDto = objectMapper.readValue(body, TextResponseDto.class);
        return textResponseDto;
    }
}
